<template>
  <el-dialog
    v-el-drag-dialog="{updataFull, updataDialogWidth}"
    :fullscreen="isfullscreen"
    :width="setDialogWidth('600px')"
    :title="$t('EDIT_FACILITY_TYPE')"
    :visible="visible"
    @open="open"
    @close="close"
  >
    <el-table
      ref="tableBox"
      class="w-100 mb-10"
      :data="tableData"
      height="350px"
      size="mini"
      border
    >
      <template slot="empty">
        <NullData />
      </template>
      <el-table-column type="index" :label="$t('SEQUENCE')" align="center" width="140">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('FACILITY_TYPE_NAME')" prop="cableLevel">
        <template v-slot="scope">
          <el-input v-if="scope.row.update" v-model.trim="scope.row.name" maxlength="32" />
          <span v-else>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('OPERATE')" class-name="operate-cell" width="80">
        <template v-slot="scope">
          <i
            v-if="scope.$index === tableData.length - 1 && tableData.filter(i => i.update).length < 4"
            class="el-icon-plus mr-10 icon-font"
            @click="addRow"
          />
          <i
            v-if="scope.row.update && !scope.row.used"
            class="el-icon-minus icon-font"
            @click="delRow(scope.row, scope.$index)"
          />
        </template>
      </el-table-column>
    </el-table>
    <template v-slot:footer>
      <el-button size="mini" @click="close">{{ $t('CANCEL') }}</el-button>
      <el-button size="mini" type="primary" @click="$debounce(save)">{{ $t('SAVE') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { deepClone } from '@/utils/common'
  import BizDictApi from '@/api/basebiz/BizDictApi'
  import FacilityApi from '@/api/oen/FacilityApi'
  import OperateLogApi from '@/api/system/OperateLogApi.js'
  export default {
    props: {
      visible: {
        type: Boolean,
        default: false
      }
    },
    inject: ['parentVM'],
    data() {
      return {
        tableData: [],
        copyTableData: [],
        delIds: []
      }
    },
    computed: {
      ...mapGetters(['dictList', 'customDictList', 'getUser', 'getUserId']),
      dicFacilityTypeList() {
        return this.customDictList.filter(i => i.type === 'FACILITY')
      }
    },
    methods: {
      open() {
        // console.log('this.dicFacilityTypeList--------', this.dicFacilityTypeList)
        const list = deepClone(this.dicFacilityTypeList)
        const ids = list.map(i => i.code)
        // 获取被使用的敷设方法
        FacilityApi.facilityTypeUsageStatus({ ids: ids.join(',') }).then(res => {
          list.forEach(item => {
            item.use = false
            item.sort = item.sort || (list.length + 1)
            if (res[item.code]) {
              item.used = true
            }
          })
          const arr1 = list.filter(i => !i.update)
          const arr2 = list.filter(i => i.update)
          this.tableData = [...arr1, ...arr2]
          this.copyTableData = deepClone(this.tableData)
        })
      },
      addRow() {
        const date = new Date()
        this.tableData.push({
          name: '',
          code: `FACILITY_SELF_${date.getTime()}`,
          update: true,
          type: 'FACILITY',
          parentId: 'FACILITY_TYPE',
          sort: this.tableData.slice(-1)[0]['sort'] + 1
        })
      },
      delRow(row, index) {
        console.log('row', row)
        this.tableData.splice(index, 1)
        if ('id' in row) this.delIds.push(row.id)// 存储需要删除的项
      },
      async save() { // 保存逻辑修改
        try {
          const selfData = this.tableData.filter(i => i.update)
          if (selfData.length && selfData.some(i => !i.name)) {
            this.$message.error(this.$t('PLEASE_COMPLETE_INFO_SAVING'))
            return
          }
          if (this.delIds.length) { // 如果有就删除
            const names = this.delIds.map(i => this.copyTableData.find(j => j.id === i).name).join()
            await BizDictApi.del({ ids: this.delIds.toString() })
            this.delIds = []
            this.addLog({
              i18nKey: 'DELETE_FACILITY_TYPE', // 删除设施类型
              object: names,
              names
            })
          }
          if (selfData.length) { // 保存/修改
            const res = await BizDictApi.saveBatch([...selfData])
            if (!res) {
              this.$message.error(this.$t('SAVEFAILED'))
              return
            }
            this.addLog({
              i18nKey: 'EDIT_FACILITY_TYPE_LOG', // 编辑设施类型
              object: '/'
            })
          }
          this.$message.success(this.$t('SAVE_SUCCESS'))
          this.$store.dispatch('getCustomDict')
          this.close()
        } catch (error) {
          console.log(error)
          this.$message.error(this.$t('SAVEFAILED'))
        }
      },
      close() {
        this.$emit('close', this.tableData)
      },
      addLog(logData) {
        let item = ''
        if (this.parentVM.functionName === 'homeTopo') {
          item = 'HOME_TOPOLOGY_MAP' // 系统首页-拓扑图
        }
        if (this.parentVM.functionName === 'homeGis') {
          item = 'HOME_GIS_MAP' // 系统首页-GIS展示
        }
        if (this.parentVM.functionName === 'facility') {
          item = 'MENU_FACILITIES_MANAGE' // 设施管理
        }
        if (this.parentVM.functionName === 'cable') {
          item = 'MENU_CABLE_MANAGER' // 光缆管理
        }
        const obj = {
          item,
          realName: this.getUser.realName,
          terminal: 'EDIT_FACILITY_TYPE', // 编辑设施类型
          object: logData.object,
          content: JSON.stringify({
            currentUserId: this.getUserId,
            ...logData
          })
        }
        // 记录导出日志
        OperateLogApi.addLog(obj)
      }
    }
  }
</script>

<style></style>
